<!--
 * @Date: 2024-12-11 16:13:30
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-02-18 10:57:20
 * @Description: 数据源设置的组件
-->
<template>
  <div>
    <el-button :plain="true" round type="primary" size="small"
      @click="handleOpen">编辑</el-button>
  </div>
</template>

<script setup>
import { watch, ref } from 'vue';

import { isEmpty } from '@hp/utils/data.js'
import { callComp } from '@/plugins/call-comp/CallCompPlugins.jsx'
import { DbSourceType } from '@hp/config/pojo'
import { defDataSource } from '@hp/panels/cfg.js'

import DbSouceDialog from './components/DbSouceDialog.vue'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  schema: { type: Object },
  config: { type: Object },
  checkedNode: { type: Object },
  modelValue: {}
})

const dataSource = ref({})
const handleOpen = () => {
  const attrs = {
    ...props,
    dataSource: dataSource.value,
  }
  delete attrs.modelValue
  callComp.open(DbSouceDialog, {
    ...attrs,
    onConfirm: (res) => {
      const result = res
      // 清除不需要的配置
      for (const item of DbSourceType.getTypes()) {
        if(item.equals(result.type)) continue;
        result[`${item.value}Config`] = JSON.parse(JSON.stringify(item.config))
      }
      emits('update:modelValue', result)
    }
  })
}

watch(
  () => props.modelValue,
  (nv) => {
    if (isEmpty(nv)) {
      dataSource.value = JSON.parse(JSON.stringify(defDataSource.dataSource))
    } else {
      dataSource.value = JSON.parse(JSON.stringify(nv))
    }
  },
  { deep: true, immediate: true }
)

</script>

<style lang="scss" scoped>
</style>